package com.party.admin.web.controller.competition;

import com.google.common.base.Strings;
import com.party.admin.biz.competition.CompProjectBizService;
import com.party.admin.biz.file.FileBizService;
import com.party.core.utils.MyBeanUtils;
import com.party.admin.utils.RealmUtils;
import com.party.admin.web.dto.AjaxResult;
import com.party.admin.web.dto.input.common.CommonInput;
import com.party.admin.web.dto.output.competition.CompetitionProjectOutput;
import com.party.common.paging.Page;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.BaseModel;
import com.party.core.model.competition.CompetitionGroup;
import com.party.core.model.competition.CompetitionMember;
import com.party.core.model.competition.CompetitionProject;
import com.party.core.model.competition.CompetitionSchedule;
import com.party.core.service.competition.ICompetitionGroupService;
import com.party.core.service.competition.ICompetitionMemberService;
import com.party.core.service.competition.ICompetitionProjectService;
import com.party.core.service.competition.ICompetitionScheduleService;
import com.party.core.service.competition.biz.CompetitionScheduleBizService;
import com.party.core.service.cos.CosBizService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 赛事项目
 *
 * @author Administrator
 */
@Controller
@RequestMapping("/competition/project")
public class CompetitionProjectController {

    @Autowired
    private ICompetitionProjectService competitionProjectService;
    @Autowired
    private ICompetitionScheduleService competitionScheduleService;
    @Autowired
    private ICompetitionMemberService competitionMemberService;
    @Autowired
    private ICompetitionGroupService competitionGroupService;
    @Autowired
    private FileBizService fileBizService;
    @Autowired
    private CosBizService cosBizService;
    @Autowired
    private CompetitionScheduleBizService competitionScheduleBizService;
    @Autowired
    private CompProjectBizService compProjectBizService;


    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 列表
     *
     * @param page
     * @return
     */
    @RequestMapping("list")
    public ModelAndView list(Page page, CompetitionProject project, CommonInput commonInput) {
        page.setLimit(15);
        project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
        ModelAndView mv = new ModelAndView("competition/projectList");
        Map<String, Object> params = CommonInput.appendParams(commonInput);
        List<CompetitionProject> competitionProjects = competitionProjectService.webListPage(project, params, page);
        List<CompetitionProjectOutput> projectOutputs = LangUtils.transform(competitionProjects, input -> {
            CompetitionProjectOutput output = CompetitionProjectOutput.transform(input);

            // 总人数
            int totalNum = competitionMemberService.listPage(new CompetitionMember(input.getId()), null).size();
            output.setTotalNum(totalNum);
            // 小组数量
            int groupNum = competitionGroupService.listPage(new CompetitionGroup(input.getId()), null).size();
            output.setGroupNum(groupNum);
            // 日程数量
            int scheduleNum = competitionScheduleService.listPage(new CompetitionSchedule(input.getId()), null).size();
            output.setScheduleNum(scheduleNum);
            // 项目详情二维码
            String filePath = fileBizService.getUploadCIPath(input.getCreateBy(), "competition");
            String qrCodeUrl = cosBizService.getPreviewPictureUrl(filePath + input.getId());
            output.setQrCodeUrl(qrCodeUrl);
            return output;
        });

        mv.addObject("projectList", projectOutputs);
        mv.addObject("input", commonInput);
        mv.addObject("project", project);
        mv.addObject("page", page);
        return mv;
    }

    /**
     * 新增/编辑表单
     *
     * @param id
     * @return
     */
    @RequestMapping("toForm")
    public ModelAndView toForm(String id) {
        ModelAndView mv = new ModelAndView("competition/projectForm");
        if (StringUtils.isNotEmpty(id)) {
            CompetitionProject project = competitionProjectService.get(id);
            mv.addObject("project", project);

            List<CompetitionSchedule> schedules = competitionScheduleService.findByProject(id);
            mv.addObject("schedules", schedules);
        }
        return mv;
    }

    /**
     * 保存
     *
     * @param project
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "save", method = RequestMethod.POST)
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult save(String startTimeStr, CompetitionProject project, BindingResult result) {
        // 数据验证
        if (result.hasErrors()) {
            List<ObjectError> allErrors = result.getAllErrors();
            String description = allErrors.get(0).getDefaultMessage();
            return AjaxResult.error(description);
        }

        try {
            if (StringUtils.isNotEmpty(startTimeStr)) {
                Date startTime = DateUtils.parse(startTimeStr, "yyyy-MM-dd HH:mm");
                project.setStartTime(startTime);
            }
            String memberId = Strings.isNullOrEmpty(project.getCreateBy()) ? RealmUtils.getCurrentUser().getId() : project.getCreateBy();
            if (StringUtils.isEmpty(project.getId())) {
                project.setDelFlag(BaseModel.DEL_FLAG_NORMAL);
                project.setCreateBy(memberId);
                project.setUpdateBy(memberId);
                competitionProjectService.insert(project);
            } else {
                CompetitionProject t = competitionProjectService.get(project.getId());
                MyBeanUtils.copyBeanNotNull2Bean(project, t);
                competitionProjectService.update(t);

                memberId = t.getCreateBy();
            }
            try {
                String filePath = fileBizService.getUploadCIPath(memberId, "competition");
                String content = "competition/all_person_rank.html?projectId=" + project.getId();
                fileBizService.uploadCloudOut(project.getId(), filePath, content, memberId);
            } catch (Exception e) {
                e.printStackTrace();
            }
            competitionScheduleBizService.saveScheduleBiz(project.getId(), project.getSchedules(), memberId);
            return AjaxResult.success();
        } catch (Exception e) {
            logger.error("保存项目异常", e);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjaxResult.error("保存项目异常");
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("delete")
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AjaxResult delete(String id) {
        List<CompetitionMember> members = competitionMemberService.list(new CompetitionMember(id));
        if (members.size() > 0) {
            return AjaxResult.error("该项目下已有人员，不能删除");
        }
        List<CompetitionGroup> groups = competitionGroupService.list(new CompetitionGroup(id));
        if (groups.size() > 0) {
            return AjaxResult.error("该项目下已有小组，不能删除");
        }
        boolean result = compProjectBizService.deleteProjectBiz(id);
        if (result) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error("删除失败");
        }
    }

    @ResponseBody
    @RequestMapping("initQrCode")
    public AjaxResult initQrCode() {
        List<CompetitionProject> competitionProjects = competitionProjectService.list(new CompetitionProject());
        for (CompetitionProject project : competitionProjects) {
            String filePath = fileBizService.getUploadCIPath(project.getCreateBy(), "competition");
            String localPath = project.getCreateBy() + "/competition/all/";
            String content = "competition/all_person_rank.html?projectId=" + project.getId();
            fileBizService.uploadCloudOut(project.getId(), filePath, localPath, project.getId(), content, project.getCreateBy());
        }
        return AjaxResult.success();
    }
}
